import { Prefab } from 'cc';
import { instantiate } from 'cc';
import { _decorator, Component, Node, tween, UITransform, v3 } from 'cc';
import { GetPlayerGoodsVoAPI, PlayerGoodsVo } from '../../GameAPI';
import { CardController } from './卡牌/CardController';
import { CardsController } from './卡牌/CardsController';
const { ccclass, property } = _decorator;

@ccclass('RightUIController')
export class RightUIController extends Component {

    //是否展开
    isOpen:boolean = false;

    //当前展开的下标
    index:number = null;

    //展出列表
    @property({ type:[Node], displayName:"展出列表" })
    lists:Node[] = [];

    @property({type:CardsController,displayName:"卡牌内容"})
    cardContent:CardsController;
    @property({type:Prefab,displayName:"卡牌"})
    cardPrefab:Prefab;

    start() {

    }

    update(deltaTime: number) {
        
    }

    //打开
    switch(event,index){

        if(!this.lists[parseInt(index)]) return;

        if(this.index === index) {
            if(this.isOpen) this.close();
            return;
        }else{
            if(this.isOpen) this.close();
        }

        this.index = index;
        this.isOpen = true;
        let ui = this.lists[parseInt(index)].getComponent(UITransform);

        console.log("open",this.lists[parseInt(index)]);
        tween(this.lists[parseInt(index)])
            .to(
                .3,
                {
                    position:v3(-ui.width - 40,0,0)
                }
            ).start();

        this.loadData();

    }

    async loadData(){

        this.cardContent.node.destroyAllChildren();

        let data:PlayerGoodsVo[] = await GetPlayerGoodsVoAPI({
            goodsPlace:true
        });

        console.log("loadData",data);

        data.forEach((vo:PlayerGoodsVo) => {

            let card = instantiate(this.cardPrefab);
            let cardController = card.getComponent(CardController);
            
            Object.keys(cardController.configs.json).forEach((key) => {
                if(cardController.configs.json[key].id === vo.goodsId){
                    cardController.type = key;
                }
            })

            cardController.updateConfig();
            card.parent = this.cardContent.node;
            
        });
        
        this.cardContent.updateCards();

    }

    //关闭
    close(){

        if(!this.isOpen) true;
        let ui = this.node.getComponent(UITransform);

        this.isOpen = false;
        this.index = null;
        
        
        console.log("close");
        this.lists.forEach(item => {
            tween(item)
                .to(
                    .3,
                    {
                        position:v3(0,0,0)
                    }
                ).start();
        })

    }


}

